<?php
class system_view_layout {
	protected $_view = null;
	protected $_contentKey = 'content';
	protected $_enabled = true;
	protected $_container = array();
	protected $_layout = 'layout';
	
	public function __construct() {
	
	}
	
	protected static $instance = null;
	static public function getInstance() {
		if(null===self::$instance) {
			self::setInstance(new self());
		}
		return self::$instance;
	}
	static public function setInstance(system_view_layout $instance) {
		self::$instance = $instance;
	}
	
	public function setLayout($name, $enabled = true) {
		$this->_layout = (string) $name;
		if($enabled) {
			$this->enableLayout();
		}
		return $this;
	}
	public function getLayout() {
		return $this->_layout;
	}
	public function disableLayout() {
		$this->_enabled = false;
		return $this;
	}
	public function enableLayout() {
		$this->_enabled = true;
		return $this;
	}
	
	public function isEnabled() {
		return $this->_enabled;
	}
	
	public function setContentKey($contentKey) {
		$this->_contentKey = (string) $contentKey;
		return $this;
	}
	public function getContentKey() {
		return $this->_contentKey;
	}
	
	public function setView(system_view_interface $view) {
		$this->_view = $view;
		return $this;
	}
	
	public function getView() {
		if(null===$this->_view) {
			$this->setView(new system_view());
		}
		return $this->_view;
	}
	
	public function __set($key, $value) {
		$this->_container[$key] = $value;
	}
	
	public function __get($key) {
		if(isset($this->_container[$key])) {
			return $this->_container[$key];
		}
		
		return null;
	}
	
	public function __isset($key) {
		return (isset($this->_container[$key]));
	}
	public function __unset($key) {
		if(isset($this->_container[$key])) {
			unset($this->_container[$key]);
		}
	}
	public function assign($spec, $value = null) {
		if(is_array($spec)) {
			$orig = $this->_container->getArrayCopy();
			$merged = array_merge($orig, $spec);
			$this->_container->exchangeArray($merged);
			return $this;
		}
		
		if(is_string($spec)) {
			$this->_container[$spec] = $value;
			return $this;
		}
	}
	public function render() {
		$view = $this->getView();
		$script = $this->getLayout().'.'.system_controller_action::$viewSuffix;
		return $view->render($script);
	}
}